package com.efounder.chat.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.widget.SecretPassInputDialog;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.util.LoadingDataUtilBlack;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的设备，多设备登录管理
 * @author will
 */
public class MultiLoginListFragment extends BaseFragment {

    public static final String TAG = "MultiLoginListFragment";
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private MultiDeviceAdapter adapter;
    private List<LoginDevice> mData = new ArrayList<>();
    private List<LoginDevice> mDataOther = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_multi_login_list, container, false);
        initView(view);
        return view;
    }



    private void initView(View view) {
        TextView tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_my_device);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new MultiDeviceAdapter(getActivity(), R.layout.item_multi_login_device, mData);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
        LoadingDataUtilBlack.show(_mActivity);
        initData();
    }

    private void initData() {

        Map<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("passWord", EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD));
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                refreshLayout.finishRefresh();
                LoadingDataUtilBlack.dismiss();
                if (response != null) {
                    LogUtils.i(response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            mData.clear();
                            mDataOther.clear();
                            //返回成功
                            JSONArray deviceArray = jsonObject.optJSONArray("sessionContextList");
                            if (deviceArray.length() > 0) {
                                for (int i = 0; i < deviceArray.length(); i++) {
                                    JSONObject deviceObj = deviceArray.optJSONObject(i);
                                    LoginDevice loginDevice = new LoginDevice();
                                    loginDevice.setName(URLDecoder.decode(deviceObj.optString("deviceModel"), "UTF-8"));
                                    loginDevice.setDeviceId(deviceObj.optString("deviceId"));
                                    loginDevice.setClientId(deviceObj.optString("clientId"));
                                    try {
                                        loginDevice.setTime(com.utilcode.util.TimeUtils
                                                .millis2String(Long.valueOf(deviceObj.optString("sessionTime"))));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    loginDevice.setType(deviceObj.optString("deviceType"));
                                    Boolean isLocal = loginDevice.getDeviceId().equals(EnvironmentVariable.getProperty("deviceId"));
                                    if(isLocal){
                                        mData.add(loginDevice);
                                    }else {
                                        mDataOther.add(loginDevice);
                                        Collections.sort(mDataOther, new Comparator<LoginDevice>() {
                                            @Override
                                            public int compare(final LoginDevice msg1, final LoginDevice msg2) {

                                                if (msg1.getTime().compareTo(msg2.getTime()) == 0) {
                                                    return 0;
                                                } else if (msg1.getTime().compareTo(msg2.getTime()) > 0) {
                                                    return -1;
                                                } else {
                                                    return 1;
                                                }
                                            }

                                        });

                                    }
                                }
                                mData.addAll(mDataOther);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort(R.string.chat_please_fail);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                refreshLayout.finishRefresh();
                ToastUtils.showShort(R.string.chat_please_fail);
                LoadingDataUtilBlack.dismiss();
            }
        });
        httpRequest.httpPost(String.format("%s/%s", EnvironmentVariable.getProperty("IMBaseUrl"),
                "IMServer/user/getSessionContextList"), params);

    }

    private void sendLogOutMsg(String clientId, String deviceId) {
        LoadingDataUtilBlack.show(_mActivity,_mActivity.getResources().getString(R.string.chat_multi_login_offLine_dialog_hint));
        Map<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("passWord", EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD));
        params.put("clientId", clientId);
        params.put("deviceId", deviceId);
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                LoadingDataUtilBlack.dismiss();
                if (response != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            //返回成功
                            ToastUtils.showShort(R.string.chat_send_message_success);
                        } else {
                            ToastUtils.showShort(R.string.chat_off_online_fail_please);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort(R.string.chat_off_online_fail_please);
                    }
                }
                refreshLayout.autoRefresh(2000);
            }

            @Override

            public void onRequestFail(int requestCode, String message) {
                LoadingDataUtilBlack.dismiss();
                ToastUtils.showShort(R.string.chat_off_online_fail_please);
            }
        });
        httpRequest.httpPost(String.format("%s/%s", EnvironmentVariable.getProperty("IMBaseUrl"),
                "IMServer/user/deviceLogout"), params);
    }

    public class MultiDeviceAdapter extends CommonAdapter<LoginDevice> {

        public MultiDeviceAdapter(Context context, int layoutId, List<LoginDevice> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final LoginDevice loginDevice, int position) {
            ImageView ivDeviceIcon;
            TextView tvDeviceName;
            TextView tvDeviceLoginTime;
            TextView tvDeviceKick;

            ivDeviceIcon = (ImageView) holder.getView(R.id.iv_device_icon);
            tvDeviceName = (TextView) holder.getView(R.id.tv_device_name);
            tvDeviceLoginTime = (TextView) holder.getView(R.id.tv_device_login_time);
            tvDeviceKick = (TextView) holder.getView(R.id.tv_device_kick);
            String type = loginDevice.getType();
            type = type.toLowerCase();
            if (type.equals("ios")) {
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_ios));
            } else if(type.equals("android")){
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_android));
            }else if(type.equals("win")){
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_win));
            }else if(type.equals("mac")){
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_mac));
            }else if(type.equals("linux")){
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_linux));
            }else {
                ivDeviceIcon.setImageDrawable(getResources().getDrawable(R.drawable.deveice_h5));
            }
            if (loginDevice.getName().isEmpty()) {
                tvDeviceName.setText(R.string.chat_not_known_d);
            }else{
                tvDeviceName.setText(loginDevice.getName());
            }
            tvDeviceLoginTime.setText(loginDevice.getTime());
            if (loginDevice.getDeviceId().equals(EnvironmentVariable.getProperty("deviceId"))) {
                tvDeviceKick.setText(R.string.chat_local_phone);
                tvDeviceKick.setBackground(null);
                tvDeviceKick.setClickable(false);
            } else {
                tvDeviceKick.setText(R.string.chat_off_online);
                tvDeviceKick.setBackground(getResources().getDrawable(R.drawable.text_button_stroke_bg));
                tvDeviceKick.setClickable(true);
                tvDeviceKick.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SecretPassInputDialog dialog = new SecretPassInputDialog(getActivity(), new SecretPassInputDialog.OnEnterClick() {
                            @Override
                            public void passVerifySuccess(String passWord) {
                                //密码正确，开始发送
                                sendLogOutMsg(loginDevice.getClientId(), loginDevice.getDeviceId());
                            }
                        });
                        dialog.getTips().setVisibility(View.GONE);
                        dialog.show();

                    }
                });
            }

           /* int size = mData.size();
            for (int i = 0; i < size; i++) {
            LoginDevice loginDevice1 =mData.get(i);
            String string = loginDevice1.getDeviceId();
                if (string.equals(EnvironmentVariable.getProperty("deviceId"))) {
                    mData.add(0,loginDevice1);
                    mData.remove(i+1);

                }
            }*/



        }
    }

    public static Date stringToDate(String dateString) {
        ParsePosition position = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateValue = simpleDateFormat.parse(dateString, position);
        return dateValue;
    }


    public static class LoginDevice {
        private String name;
        private String time;
        private String type;
        private String deviceId;
        private String clientId;

        public LoginDevice() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getDeviceId() {
            return deviceId;
        }

        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }

        public String getClientId() {
            return clientId;
        }

        public void setClientId(String clientId) {
            this.clientId = clientId;
        }
    }
}
